<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Surat extends CI_Controller {	
	
	function index($kap='')
	{
		if(!$this->session->userdata('name')):
			redirect('auth');
			
		endif;
		
		if($kap==''):
				redirect('surat/index/esr/');
		endif;
		$var['title']	= 'Surat Keluar';
		$var['kap']		= $kap;
		$no = $this->session->userdata('no_surat');
		$kl = $this->session->userdata('klien_surat');
		$ta = $this->session->userdata('tgl_surat_awal');
		$tk = $this->session->userdata('tgl_surat_akhir');
		$var['surats']	= $this->surats->getData($kap,$no,$kl,$ta,$tk);
		$var['content'] = 'index-surat';
		$this->load->view('index',$var);
	}
	
	function action(){
		if($this->session->userdata('no_surat')==''):
			$surat=array('no_surat'=>$this->input->post('no'),'klien_surat'=>$this->input->post('s'));
		else:
			$surat=array('no_surat'=>'','klien_surat'=>'');
		endif;
		$this->session->set_userdata($surat);
		redirect($this->input->server('HTTP_REFERER'),301);
	}
	
	function date(){
		$start_date = $this->input->post('yyyy').'-'.$this->input->post('mm').'-'.$this->input->post('dd');
		$end_date   = $this->input->post('yyyy2').'-'.$this->input->post('mm2').'-'.$this->input->post('dd2');
		if($this->session->userdata('tgl_surat_awal')==''):
			$surat=array('tgl_surat_awal'=>$start_date,'tgl_surat_akhir'=>$end_date);
		else:
			$surat=array('tgl_surat_awal'=>'','tgl_surat_akhir'=>'');
		endif;
		$this->session->set_userdata($surat);
		redirect($this->input->server('HTTP_REFERER'),301);
	}
	
	function excel(){
		//$this->db->use_table('surats');
		$this->db->select('no_surat', 'tanggal');
	    // run joins, order by, where, or anything else here
		$this->db->order_by('tanggal','DESC');
	    $query = $this->db->get('surats');
        to_excel($query,'surats'); // filename is optional, without it, the plugin will default to 'exceloutput'
	}
	
	public function add($kap)
	{
		$var['title']	= 'Add Surat';
		$var['kap']		=  $kap;
		$var['no']		= $this->surats->getLatestPK($kap,'no');
		$var['content'] = 'add-surat';
		$this->load->view('index',$var);
	}
	
	function save($kap=''){
		if($this->input->post('nama_klien')):
			$this->surats->getSave(strtoupper($kap));
		endif;
		redirect('surat/index/'.$kap,301);
	}
	
	public function edit($id,$kap)
	{
		$var['title']	= 'Edit Surat';
		$var['kap']		=  $kap;
		$var['surat']	= $this->surats->getID($id);
		$var['no']		= $this->surats->getLatestPK($kap,'no');
		$var['content'] = 'edit-surat';
		$this->load->view('index',$var);
	}
	
	function update($kap=''){
		if($this->input->post('nama_klien')):
			$this->surats->getUpdate(strtoupper($kap));
		endif;
		redirect('surat/index/'.$kap,301);
	}
	
	function remove($id){
		if($id):
			$this->surats->getRemove($id);
		endif;
		redirect($this->input->server('HTTP_REFERER'),301);
	}
	
}
